<template>
  <view class="order-page">
    <!-- 占位：避免原生 titleNView 覆盖顶部内容 -->
    <view class="top-space"></view>
    
    <!-- 订单类型筛选 -->
    <view class="filter-tabs">
      <view 
        class="tab" 
        :class="{ active: activeTab === 'published' }"
        @click="switchTab('published')"
      >
        我发布的
      </view>
      <view 
        class="tab" 
        :class="{ active: activeTab === 'accepted' }"
        @click="switchTab('accepted')"
      >
        我接取的
      </view>
    </view>

    <!-- 搜索框（放在筛选和内容之间） -->
    <view class="search-container">
      <view class="search-inner">
        <!-- 使用原生 input 并保留 v-model，这在 uni-app 中会正常工作 -->
        <input
          class="search-input"
          placeholder="搜索订单标题或用户"
          v-model="searchKeyword"
          @input="onSearchInput"
          @confirm="handleSearch"
        />
        <view
          v-if="searchKeyword"
          class="clear-btn"
          @click="clearSearch"
        >✕</view>
      </view>
    </view>

    <!-- 主内容区 -->
    <scroll-view 
      class="content"
      :scroll-y="true"
    >
      <view class="grid">
        <view 
          v-for="(order, idx) in filteredOrders" 
          :key="idx" 
          class="card"
          @click="goToOrderDetail(order)"
        >
          <view 
            class="media"
            :class="{ none: !order.image }"
            :style="order.image ? 'background-image: url(' + order.image + ')' : ''"
          ></view>
          <view class="body">
            <view class="title">{{ order.title }}</view>
            <view class="meta">
              <view class="user">
                <view class="avatar" :style="avatarStyle(order)">{{ (order.username || '').slice(0,1) }}</view>
                <view class="username">{{ order.username }}</view>
              </view>
              <view class="price">￥{{ order.price }}</view>
            </view>
            <!-- 订单状态 -->
            <view class="order-status" :class="order.statusClass">{{ order.status }}</view>
          </view>
        </view>
        
        <!-- 空状态 -->
        <view v-if="filteredOrders.length === 0" class="empty">
          <text>暂无相关订单</text>
        </view>
      </view>
      
      <!-- 底部导航占位 -->
      <view class="bottom-placeholder"></view>
    </scroll-view>
  </view>
</template>

<script>
export default {
  name: 'OrderPage',
  data() {
    return {
      activeTab: 'published', // 默认显示我发布的订单
      searchKeyword: '',
      orders: [
        { 
          id: 1,
          type: 'published',
          title: '帮忙照看宠物一整天', 
          username: '李阿姨', 
          price: 50, 
          image: 'https://images.unsplash.com/photo-1543466835-00a7907e9de1?auto=format&fit=crop&w=800&q=60',
          status: '已完成',
          statusClass: 'completed'
        },
        { 
          id: 2,
          type: 'published',
          title: '手机紧急维修：屏幕需要更换并同步数据（急）', 
          username: '阿凯', 
          price: 300, 
          image: 'https://images.unsplash.com/photo-1510557880182-3f8a7f9b4f6d?auto=format&fit=crop&w=800&q=60',
          status: '进行中',
          statusClass: 'in-progress'
        },
        { 
          id: 3,
          type: 'accepted',
          title: '代购：某专业考试复习资料（电子）', 
          username: '米米', 
          price: 20, 
          image: '',
          status: '待接取',
          statusClass: 'pending'
        },
        { 
          id: 4,
          type: 'accepted',
          title: '小区帮取快递（需楼下取件）', 
          username: '玲玲', 
          price: 10, 
          image: 'https://images.unsplash.com/photo-1546525848-3ce03ca516f6?auto=format&fit=crop&w=800&q=60',
          status: '正在仲裁',
          statusClass: 'in-arbitration'
        },
        { 
          id: 5,
          type: 'published',
          title: '阳台深度清洁（1小时）', 
          username: '家政小王', 
          price: 80, 
          image: 'https://images.unsplash.com/photo-1503342452485-86f7f26d2f48?auto=format&fit=crop&w=800&q=60',
          status: '待接取',
          statusClass: 'pending'
        },
        { 
          id: 6,
          type: 'accepted',
          title: '点餐并帮忙取餐（代付）', 
          username: '小刘', 
          price: 12, 
          image: '',
          status: '已完成',
          statusClass: 'completed'
        }
      ]
    }
  },
  
  computed: {
    filteredOrders() {
      const tabFiltered = this.orders.filter(order => order.type === this.activeTab);
      const kw = (this.searchKeyword || '').trim().toLowerCase();
      if (!kw) return tabFiltered;

      return tabFiltered.filter(order => {
        const title = (order.title || '').toLowerCase();
        const username = (order.username || '').toLowerCase();
        return title.includes(kw) || username.includes(kw);
      });
    }
  },
  
  methods: {
    // 切换订单类型
    switchTab(tab) {
      this.activeTab = tab;
    },
    
    // 跳转到订单详情页
    goToOrderDetail(order) {
      const orderData = encodeURIComponent(JSON.stringify(order));
      uni.navigateTo({
        url: `/pages/order/order-detail?orderData=${orderData}`
      });
    },
    
    // 头像样式辅助
    avatarStyle(order) {
      if (!order.username) return {}
      const colors = [
        'linear-gradient(135deg,#6dd5ed 0%,#2193b0 100%)',
        'linear-gradient(135deg,#f6d365 0%,#fda085 100%)',
        'linear-gradient(135deg,#a1c4fd 0%,#c2e9fb 100%)',
        'linear-gradient(135deg,#d4fc79 0%,#96e6a1 100%)'
      ]
      const index = order.username.charCodeAt(0) % colors.length
      return {
        background: colors[index],
        color: '#fff'
      }
    },

    // 搜索相关
    onSearchInput(e) {
      // uni-app 的 input 事件在不同平台上可能有不同结构
      // v-model 已经同步了 searchKeyword，但为了兼容事件结构我们也做一次兼容赋值
      const val = (e && (e.detail && e.detail.value)) || e && e.target && e.target.value || this.searchKeyword;
      this.searchKeyword = val;
      // 如果需要做防抖，可在这里实现
    },

    handleSearch() {
      // 回车确认时的处理（当前逻辑由 computed 自动过滤）
      uni.showToast({ title: `搜索：${this.searchKeyword || '全部'}`, icon: 'none' });
    },

    clearSearch() {
      this.searchKeyword = '';
    }
  }
}
</script>

<style scoped>
.order-page {
  display: flex;
  flex-direction: column;
  height: 100vh;
  background: linear-gradient(180deg, #eef2ff 0%, #f8fafc 100%);
  box-sizing: border-box;
}

/* 顶部占位：让页面内容不被原生 titleNView 覆盖 */
/* .top-space {
  height: 54px;
  width: 100%;
} */

/* 筛选标签 */
.filter-tabs {
  display: flex;
  background: #ffffff;
  border-bottom: 1px solid #eee;
  padding: 0 12px;
}

.tab {
  flex: 1;
  text-align: center;
  padding: 16px 0;
  font-size: 16px;
  color: #8b94a6;
  position: relative;
}

.tab.active {
  color: #56BAEC;
  font-weight: bold;
}

.tab.active::after {
  content: '';
  position: absolute;
  bottom: 0;
  left: 50%;
  transform: translateX(-50%);
  width: 40px;
  height: 3px;
  background: #56BAEC;
  border-radius: 3px;
}

/* 搜索框 */
.search-container {
  padding: 10px 12px;
  background: transparent;
}
.search-inner {
  background: #ffffff;
  border-radius: 10px;
  padding: 8px 10px;
  display: flex;
  align-items: center;
  gap: 8px;
  box-shadow: 0 6px 14px rgba(18,24,40,0.04);
}
.search-input {
  flex: 1;
  border: none;
  outline: none;
  font-size: 14px;
  line-height: 1.2;
  padding: 4px 0;
  background: transparent;
}
.clear-btn {
  font-size: 14px;
  padding: 4px;
}

/* 内容区域 */
.content {
  flex: 1;
  padding: 12px;
  box-sizing: border-box;
}

/* 网格布局 */
.grid {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 12px;
}

/* 卡片样式 */
.card {
  background: #ffffff;
  border-radius: 12px;
  overflow: hidden;
  box-shadow: 0 8px 18px rgba(18, 24, 40, 0.06);
  cursor: pointer;
  transition: transform 0.18s ease, box-shadow 0.18s ease;
  display: flex;
  flex-direction: column;
}
.card:active {
  transform: translateY(-2px);
  box-shadow: 0 18px 36px rgba(18, 24, 40, 0.12);
}

.media {
  height: 160px;
  display: block;
  background: linear-gradient(0deg, rgba(0,0,0,0.16), rgba(0,0,0,0.02)), 
              url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" width="800" height="500"><rect width="100%" height="100%" fill="%23e6eef7"/><text x="50%" y="50%" dominant-baseline="middle" text-anchor="middle" font-size="34" fill="%2399a6b8">图片预览</text></svg>') center/cover no-repeat;
  background-size: cover;
  background-position: center;
}
.media.none {
  height: 0;
  padding: 0;
}

.card .media.none + .body {
  justify-content: space-between;
  display: flex;
  flex-direction: column;
  padding-top: 12px;
  padding-bottom: 12px;
}

.card .media.none + .body .meta {
  margin-top: auto;
}

.body {
  padding: 10px 12px;
  display: flex;
  flex-direction: column;
  gap: 8px;
  flex: 1;
}

.title {
  font-size: 15px;
  font-weight: 700;
  color: #16202b;
  line-height: 1.3;
}

.meta {
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 8px;
}

.price {
  background: linear-gradient(135deg, #6dd5ed 0%, #2193b0 100%);
  -webkit-background-clip: text;
  background-clip: text;
  color: transparent;
  font-weight: 800;
}

.user {
  display: flex;
  align-items: center;
  gap: 8px;
}

.avatar {
  width: 34px;
  height: 34px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #fff;
  font-weight: 700;
}

.username {
  font-size: 13px;
  color: #8b94a6;
}

/* 订单状态 */
.order-status {
  align-self: flex-start;
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 12px;
  font-weight: 500;
}

.pending {
  background: #fff3cd;
  color: #856404;
}

.in-progress {
  background: #cce5ff;
  color: #004085;
}

.completed {
  background: #d4edda;
  color: #155724;
}

.in-arbitration {
  background: #f8d7da;
  color: #721c24;
}

.empty {
  grid-column: 1 / -1;
  text-align: center;
  padding: 60px 20px;
  color: #8b94a6;
}

/* 底部导航占位 */
.bottom-placeholder {
  height: 20px;
}
</style>
